import { REFEREE_ID, MODULES } from '@/store/mutation-types'
import storage from '@/utils/storage'

const app = {
  state: {
    // 当前商城的ID
    storeId: null,
    // 当前终端平台
    platform: '',
    // 推荐人ID
    refereeId: null,
    // 开启的功能模块
    modules: []
  },

  mutations: {
    SET_STORE_ID: (state, value) => {
      state.storeId = value
    },
    SET_PLATFORM: (state, value) => {
      state.platform = value
    },
    SET_REFEREE_ID: (state, value) => {
      state.refereeId = value
    },
    SET_MODULES: (state, value) => {
      state.modules = value
    },
  },

  actions: {

    // 记录推荐人ID
    setRefereeId({ commit }, value) {
      const store = this
      const refereeId = parseInt(value)
      return new Promise((resolve, reject) => {
        if (refereeId > 0 && store.getters.userId != refereeId) {
          // 保存推荐人ID到缓存
          storage.set(REFEREE_ID, refereeId)
          // 记录到store全局变量
          commit('SET_REFEREE_ID', refereeId)
          resolve()
        }
      })
    },

    // 记录开启的功能模块
    SetModules({ commit }, modules) {
      return new Promise((resolve, reject) => {
        storage.set(MODULES, modules)
        commit('SET_MODULES', modules)
        resolve()
      })
    }

  }
}

export default app